import Vue from 'vue'
import {
	login,
	getUserInfo,
	logout
} from '@/axios/service/loginApi'
import {
	ACCESS_TOKEN
} from '@/store/mutation-types'


const user = {
	state: {
		token: '',
		name: '',
		loginName: '',
		welcome: '',
		avatar: '',
		roles: [],
		info: {}
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_NAME: (state, {
			name,
			welcome
		}) => {
			state.name = name
			state.welcome = welcome
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
		},
		SET_INFO: (state, info) => {
			state.info = info
		},
		SET_LOGIN_NAME: (state, loginName) => {
			state.loginName = loginName
		}
	},

	actions: {
		// 登录
		Login({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				login(userInfo).then(data => {
					window.console.log(data)
					
					if( !data.status ){
						// const token = Vue.ls.get(ACCESS_TOKEN)
						Vue.ls.set(ACCESS_TOKEN, data.access_token, 7 * 24 * 60 * 60 * 1000)
						commit('SET_TOKEN', data.access_token)
						// commit('SET_LOGIN_NAME', userInfo.loginName)
						resolve("登陆成功")
					} else{
						reject(data.message)
					}
					
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登录
		GetUserInfo({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				getUserInfo(userInfo).then(response => {
					const result = response.status;
					if( result == 0){
						const user = response.result;
						commit('SET_AVATAR', user.avatar)
						commit('SET_LOGIN_NAME', user.loginName)
						commit('SET_NAME', {name:user.userName,welcome:''})
						resolve(user)
					} else{
						reject(response.message)
					}
					
				}).catch(error => {
					reject(error)
				})
			})
		},
		
		
		// 登出
		Logout({
			commit,
			state
		}) {
			return new Promise((resolve) => {
				logout({"accessToken":state.token}).then(() => {
					resolve()
				}).catch(() => {
					resolve()
				}).finally(() => {
					commit('SET_TOKEN', '')
					commit('SET_ROLES', [])
					Vue.ls.remove(ACCESS_TOKEN)
				})
			})
		}
	}
}

export default user
